/**
 * 
 */
package com.oc.mba.ui;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.umipay.android.UmiPaySDKManager;
import net.umipay.android.UmiPaymentInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.lurencun.android.support.ui.BackUIActivity;
import com.lurencun.android.support.widget.CommonAdapter;
import com.oc.mba.AppSetting;
import com.oc.mba.R;
import com.oc.mba.entity.OcPaper;
import com.oc.mba.entity.PaidPaper;
import com.oc.mba.entity.Question;
import com.oc.mba.http.HttpHandler;
import com.oc.mba.http.RequestParams;
import com.oc.mba.presist.DataHelper;
import com.oc.mba.presist.Profile;
import com.oc.mba.res.PaperAdapter;
import com.oc.mba.util.CommonUtil;
import com.oc.mba.util.DESEncrypt;
import com.oc.mba.util.GsonUtil;
import com.oc.mba.util.HttpUtil;
import com.oc.mba.util.MD5;
import com.oc.mba.util.ProfileUtil;

/**
 * 
 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
 * @date 2012-2-24
 */
public class CategoryActivity extends BackUIActivity {

	private Context mContext;
	private DataHelper dataHelper;
	private Profile profile;
	
	@Override
	protected void onCreateEx(Bundle savedInstanceState) {
		mContext = this;
		dataHelper = new DataHelper(mContext);
		Intent intent = getIntent();
		String title = intent.getStringExtra(AppSetting.MENU_TITLE);

		TextView titleView = (TextView) findViewById(R.id.app_title);
		titleView.setText(title);
		profile = ProfileUtil.getInstance().getProfile(mContext);
		
		// 网络可用
		if (CommonUtil.isNetworkAvailable(mContext)) {
			// 加载试卷
			loadPapers();
		}
		// 网络不可用
		else {
		}
	}
	
	// 接收adapter点击事件
	final Handler adapterHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			System.out.println("adapterHandler handle:" + msg.obj.toString());
			switch (msg.what) {
				case 0:
					if (!CommonUtil.isNetworkAvailable(mContext)) {
						Toast.makeText(mContext,"网络不可用，请打开或检查网络设置。", Toast.LENGTH_SHORT).show();
					} else {
						OcPaper paper = (OcPaper) msg.obj;
						downloadPaper(paper);
					}
					break;
				// 购买试卷
				case 1:
					if (!CommonUtil.isNetworkAvailable(mContext)) {
						Toast.makeText(mContext,"网络不可用，请打开或检查网络设置。", Toast.LENGTH_SHORT).show();
					} else {
						Integer paperID = (Integer) msg.obj;
						// 请求服务器，取得订单号
						getOrderIDForPaper(paperID);
					}
					break;
				default: break;
			}
		}
	};
		
	/**
	 * 下载试题
	 * @param paper
	 */
	private void downloadPaper(final OcPaper paper) {
		// 查询试卷返回处理Handler
		final HttpHandler paperHttpHandler = new HttpHandler(mContext, true) {

			@Override
			protected void success(String obj) {
				super.success(obj);
				try {
					Map<String, Object> map = GsonUtil.stm(obj);
					String questionString = GsonUtil.otj(map.get("questionList"));
					List<Question> questionList = GsonUtil.stl(questionString, new TypeToken<List<Question>>() {}.getType());
					// 保存试题
					savePaper(paper, questionList);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			protected void failure(String obj) {
				super.failure(obj);
			}
		};
		
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(hexRandom + "" + profile.getAndroidID());
		RequestParams params = new RequestParams();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "201");
		reqMap.put("deviceID", profile.getDeviceID());
		reqMap.put("paperID", paper);
		reqMap.put("secureKey", md5Key);
		params.put("req", GsonUtil.otj(reqMap));
		
		try {
			HttpUtil.getInstance().post(params, paperHttpHandler);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	private void loadLocalPaperList(String obj) {
		ListView list = (ListView) findViewById(R.id.list_container);
		CommonAdapter<OcPaper> adapter = new PaperAdapter(this, adapterHandler);
		try {
			
			if (obj != null) {
				Map<String, Object> map = GsonUtil.stm(obj);
				String papers = GsonUtil.otj(map.get("papers"));
				String paidPapers = GsonUtil.otj(map.get("paid_papers"));
				List<OcPaper> paperList = GsonUtil.stl(papers, new TypeToken<List<OcPaper>>() {}.getType());
				List<PaidPaper> paidPaperList = GsonUtil.stl(paidPapers, new TypeToken<List<PaidPaper>>() {}.getType());
				// 判断试题是否已经付费
				for (OcPaper paper : paperList) {
					for (PaidPaper paidPaper : paidPaperList) {
						if (paper.getId() == paidPaper.getPaperId()) {
							paper.setPaid(true);
							break;
						}
					}
				}
				adapter.updateDataCache(paperList);
			}
			
			list.setAdapter(adapter);
			list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 加载列表
	 * @param profile
	 */
	private void loadPapers() {

		// 查询试卷返回处理Handler
		final HttpHandler paperHttpHandler = new HttpHandler(mContext, true) {

			@Override
			protected void success(String obj) {
				super.success(obj);
				loadLocalPaperList(obj);
			}

			@Override
			protected void failure(String obj) {
				super.failure(obj);
				loadLocalPaperList(null);
			}
		};
		
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(hexRandom + "" + profile.getAndroidID());
		RequestParams params = new RequestParams();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "200");
		reqMap.put("deviceID", profile.getDeviceID());
		reqMap.put("secureKey", md5Key);
		params.put("req", GsonUtil.otj(reqMap));
		
		try {
			HttpUtil.getInstance().post(params, paperHttpHandler);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 购买会员
	 * @param profile
	 */
	private void getOrderIDForPaper(Integer paperID) {

		// 查询试卷返回处理Handler
		final HttpHandler paperHttpHandler = new HttpHandler(mContext, true) {

			@Override
			protected void success(String obj) {
				super.success(obj);
				try {
					Map<String, Object> map = GsonUtil.stm(obj);
					Integer result = GsonUtil.oti(map.get("Result"));
					// 操作成功
					if (result == 0) {
						String orderID = GsonUtil.ots(map.get("orderID"));
						// 购买试题
						buyPaper(orderID);
					}
					// 操作失败
					else {
						Log.d("------", "getOrderID failure. result=" + result);
					}
				} catch (Exception e) {
					Log.e("------", "getOrderID error.", e);
				}
			}

			@Override
			protected void failure(String obj) {
				super.failure(obj);
				Log.e("------", obj);
			}

		};
		
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(hexRandom + "" + profile.getAndroidID());
		RequestParams params = new RequestParams();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "301");
		reqMap.put("deviceID", profile.getDeviceID());
		reqMap.put("paperID", paperID);
		reqMap.put("secureKey", md5Key);
		params.put("req", GsonUtil.otj(reqMap));
		try {
			HttpUtil.getInstance().post(params, paperHttpHandler);
		} 
		catch (UnsupportedEncodingException e) {
			Log.e("------", "Req301 http error.", e);
		}
	}
	
	/**
	 * 购买会员
	 * @param profile
	 */
	private void getOrderIDForVIP() {

		// 查询试卷返回处理Handler
		final HttpHandler paperHttpHandler = new HttpHandler(mContext, true) {

			@Override
			protected void success(String obj) {
				super.success(obj);
				Log.d("------", obj);
				try {
					Map<String, Object> map = GsonUtil.stm(obj);
					Integer result = GsonUtil.oti(map.get("Result"));
					// 操作成功
					if (result == 0) {
						String orderID = GsonUtil.ots(map.get("orderID"));
						buyVIP(orderID);
					}
					// 操作失败
					else {
						Log.d("------", "getOrderID failure. result=" + result);
					}
				} catch (Exception e) {
					Log.e("------", "getOrderID error.", e);
				}
			}

			@Override
			protected void failure(String obj) {
				super.failure(obj);
			}
		};
		
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(hexRandom + "" + profile.getAndroidID());
		RequestParams params = new RequestParams();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "302");
		reqMap.put("deviceID", profile.getDeviceID());
		reqMap.put("secureKey", md5Key);
		params.put("req", GsonUtil.otj(reqMap));
		try {
			HttpUtil.getInstance().post(params, paperHttpHandler);
		} catch (UnsupportedEncodingException e) {
			Log.e("------", "Req302 http error.", e);
		}
	}
	
	/**
	 * 购买会员
	 * @param orderID
	 */
	private void buyPaper(String orderID) {
		UmiPaymentInfo paymentInfo = new UmiPaymentInfo();
		paymentInfo.setAmount(1);
		paymentInfo.setCustomInfo(orderID);
		paymentInfo.setSinglePayMode(true);
		UmiPaySDKManager.showPayView(this, paymentInfo);
	}
	
	/**
	 * 购买会员
	 * @param orderID
	 */
	private void buyVIP(String orderID) {
		UmiPaymentInfo paymentInfo = new UmiPaymentInfo();
		paymentInfo.setAmount(1);
		paymentInfo.setCustomInfo(orderID);
		paymentInfo.setSinglePayMode(true);
		UmiPaySDKManager.showPayView(this, paymentInfo);
	}
	
	/**
	 * 保存试题
	 * @param paper
	 * @param questionList
	 */
	private void savePaper(OcPaper paper, List<Question> questionList) {
		
	}
	
	private DataHelper getHelper() {
		return dataHelper;
	}

	@Override
	protected int getContentViewLayoutId() {
		return R.layout.category;
	}

	@Override
	protected int getBackButtonResId() {
		return R.id.back_button;
	}

	@Override
	protected boolean isConfirmBack() {
		return false;
	}

}
